<?php

namespace api\modules\v1_clinic\forms;

use Yii;
use common\models\api\AccessToken;
use common\models\member\Member;
use yii\web\HttpException;

/**
 * Class LoginForm
 * @package api\modules\v1_clinic\forms
 *
 */
class LoginForm extends \common\models\member\LoginForm
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required', 'message' => '{attribute}不能为空'],
            ['password', 'validatePassword'],
            ['username', 'checkUser'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => '帐号',
            'password' => '密码',
        ];
    }

    /**
     * 用户登录
     *
     * @return mixed|null|static
     * @throws HttpException
     */
    public function getUser()
    {
        if ($this->_user == false) {
            // email 登录
            /*if (strpos($this->username, "@")) {
                $this->_user = Member::findOne(['email' => $this->username, 'status' => 1]);
            } else {
                $this->_user = Member::findByUsername($this->username);
            }*/
            // 查询用户信息
            $member = Yii::$app->services->member->getInfo([
                'mobile' => $this->username,
                'status' => Member::STATUS_ENABLE
            ], 0);

            if (!$member) {
                throw new HttpException(422, '用户不存在');
            }

            $this->_user = $member;
        }

        return $this->_user;
    }

    public function checkUser($attribute)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            // 超管不验证
            if ($user->is_super == Member::IS_SUPER_YES) {
                return true;
            }

            // 用户属性列表
            $memberAttrList = Yii::$app->services->attr->findList([
                'member_id' => $user->id,
            ]);

            $isError = true;
            foreach ($memberAttrList as $row) {
                if ($row['project_id'] && $row['department_id']) {
                    $isError = false;
                    break;
                }
            }
            $isError && $this->addError($attribute, '账户未绑定项目或部门');
        }
    }
}
